/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Fserver.java
 *
 * Created on 2 mai 2011, 23:04:06
 */
package frame;


import java.awt.Dimension;
import java.awt.Toolkit;
import java.util.Vector;
import javax.swing.JOptionPane;
import server.Server;
import user.User;
import user.UserManager;
import javax.swing.table.DefaultTableModel;
import server._ZoneExchange;

/**
 *
 * @author sz
 */
public class Fserver extends javax.swing.JFrame {

    /** Creates new form Fserver */
    public Fserver() {
        tm1 = new DefaultTableModel();
        tm2 = new DefaultTableModel();
        tm1.setColumnIdentifiers(cols);
        tm2.setColumnIdentifiers(cols);
        initComponents();
        this.setCenter();
        server=new Server();
        this.textIp.setText(server.getHostName());
        this.textPort.setText(server.getPort());
        this.setSize(500,650);
        users=new UserManager();
        this.updateUsers(users.getAllUsers());
        
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        table = new javax.swing.JTabbedPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        tableOnline = new javax.swing.JTable();
        jScrollPane2 = new javax.swing.JScrollPane();
        tableAllUser = new javax.swing.JTable();
        line = new javax.swing.JSeparator();
        bstart = new javax.swing.JButton();
        bstop = new javax.swing.JButton();
        pConfig = new javax.swing.JPanel();
        labelIp = new javax.swing.JLabel();
        textIp = new javax.swing.JTextField();
        labelPort = new javax.swing.JLabel();
        textPort = new javax.swing.JTextField();
        bset = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jScrollPane1.setAutoscrolls(true);

        tableOnline.setAutoCreateRowSorter(true);
        tableOnline.setModel(this.tm1);
        jScrollPane1.setViewportView(tableOnline);

        table.addTab("User On line", jScrollPane1);

        jScrollPane2.setAutoscrolls(true);

        tableAllUser.setAutoCreateRowSorter(true);
        tableAllUser.setModel(this.tm2);
        jScrollPane2.setViewportView(tableAllUser);

        table.addTab("All Users", jScrollPane2);

        bstart.setText("Start");
        bstart.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bstartActionPerformed(evt);
            }
        });

        bstop.setText("Stop");
        bstop.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bstopActionPerformed(evt);
            }
        });

        pConfig.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        labelIp.setText("ServerIp：");

        textIp.setText("jTextField1");

        labelPort.setText("Port：");

        textPort.setText("jTextField2");

        bset.setText("Set");
        bset.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bsetActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout pConfigLayout = new javax.swing.GroupLayout(pConfig);
        pConfig.setLayout(pConfigLayout);
        pConfigLayout.setHorizontalGroup(
            pConfigLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pConfigLayout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addComponent(labelIp)
                .addGap(66, 66, 66)
                .addComponent(textIp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(106, 106, 106)
                .addComponent(labelPort)
                .addGap(45, 45, 45)
                .addComponent(textPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 136, Short.MAX_VALUE)
                .addComponent(bset)
                .addGap(38, 38, 38))
        );
        pConfigLayout.setVerticalGroup(
            pConfigLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pConfigLayout.createSequentialGroup()
                .addContainerGap(12, Short.MAX_VALUE)
                .addGroup(pConfigLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelIp)
                    .addComponent(textIp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(labelPort)
                    .addComponent(textPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(bset))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(line, javax.swing.GroupLayout.DEFAULT_SIZE, 685, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGap(112, 112, 112)
                .addComponent(bstart)
                .addGap(98, 98, 98)
                .addComponent(bstop)
                .addContainerGap(359, Short.MAX_VALUE))
            .addComponent(table, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 685, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(pConfig, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bstart)
                    .addComponent(bstop))
                .addGap(9, 9, 9)
                .addComponent(line, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(table, javax.swing.GroupLayout.PREFERRED_SIZE, 212, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(pConfig, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(13, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void bstartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bstartActionPerformed
        // TODO add your handling code here:
       
        server.run(this);
        if(!server.isRunStatus())
        {
          JOptionPane.showMessageDialog(this, "server can't be started",
						"Fail start server", JOptionPane.ERROR_MESSAGE);
        }
        {
        bstart.setEnabled(false);
        bset.setEnabled(false);
        users= new UserManager();
        User[] tmp = users.getAllUsers();
        
        }
        
    }//GEN-LAST:event_bstartActionPerformed

    private void bstopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bstopActionPerformed
        // TODO add your handling code here:
        System.exit(0);
    }//GEN-LAST:event_bstopActionPerformed

    private void bsetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bsetActionPerformed
        // TODO add your handling code here:
        String tmpIp=this.textIp.getText();
        String tmpPort=this.textPort.getText();
        if(tmpIp.matches("\\d+\\.\\d+\\.\\d+\\.\\d+")
				&& tmpPort.matches("\\d{1,5}"))
        {
           server.setHostName(tmpIp);
           server.setPort(tmpPort);
        }
        else
        {
        JOptionPane.showMessageDialog(this, "Information typed is not correct",
						"Fail configuration", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_bsetActionPerformed
 private void setCenter() {
		Dimension sizeScreen = Toolkit.getDefaultToolkit().getScreenSize();
		Dimension sizeAppli = getSize();
		setLocation((sizeScreen.width - sizeAppli.width) / 2,
				(sizeScreen.height - sizeAppli.height) / 2);
	}

public void updateUserOnline(String[] id) {
		if (id == null)
			return;

		int count = id.length;
		User user = null;

		tm1.getDataVector().clear();
		tm1.fireTableDataChanged();
		for (int i = 0; i < count; i++) {
			user = users.getUserById(id[i]);
			String[] rowData = { user.getUserId(), user.getUserName(), 
                                 user.getSex(),user.getBirthDay(),user.getEmail(),user.getTelNumber()};
			tm1.addRow(rowData);
		}
	}

	public void updateUsers(User[] users) {
		if (users == null)
			return;
		tm2.getDataVector().clear();
		tm2.fireTableDataChanged();
		for (int i = 0; i < users.length; i++) {
			String[] rowData = { users[i].getUserId(), users[i].getUserName(),
					users[i].getSex(),users[i].getBirthDay(),users[i].getEmail(),
                                        users[i].getTelNumber()};
			tm2.addRow(rowData);
		}
	}
	
	public void addOnlineUser(User user){
		if(user==null) return;
		String[]rowdata={user.getUserId(), user.getUserName(), 
                                 user.getSex(),user.getBirthDay(),user.getEmail(),user.getTelNumber()};
		tm1.addRow(rowdata);
	}

	public void removeOnlineUser(String id){
		if(id==null||id=="") return;
		Vector v=tm1.getDataVector();
		int size=v.size();
		for(int i=0;i<size;i++){
			if(((Vector)v.elementAt(i)).elementAt(0).toString().equals(id)){
				v.remove(i);
				break;
			}
		}
		tm1.fireTableDataChanged();
	}
 
 
 
 /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Fserver().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bset;
    private javax.swing.JButton bstart;
    private javax.swing.JButton bstop;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel labelIp;
    private javax.swing.JLabel labelPort;
    private javax.swing.JSeparator line;
    private javax.swing.JPanel pConfig;
    private javax.swing.JTabbedPane table;
    private javax.swing.JTable tableAllUser;
    private javax.swing.JTable tableOnline;
    private javax.swing.JTextField textIp;
    private javax.swing.JTextField textPort;
    // End of variables declaration//GEN-END:variables
    private Server server=null;
    private UserManager users=null;
    private DefaultTableModel tm1, tm2;
    private String[] cols = { "ID", "UserName", "Sex","BirthDay","Email","TelNumber" };

    

}
